package com.caiyi.financial.nirvana.sms.service;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.base.service.BaseService;
import com.caiyi.financial.nirvana.sms.entity.SmsAccountBlacklist;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.enums.SubscribeEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.mapper.SmsAccountBlacklistMapper;
import com.youyu.common.api.Result;
import com.youyu.common.enums.BaseResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class SmsAccountBlacklistService extends BaseService<SmsAccountBlacklist> {

    @Autowired
    private SmsAccountBlacklistMapper smsAccountBlacklistMapper;

    public Result addAccountBlacklist(SmsAccountBlacklist smsAccountBlacklist) {
        Result result = new Result();
        try {
            if (isExistAccountBlacklist(smsAccountBlacklist)) {
                result.setCode(ReturnCodeEnum.FAILED.code);
                result.setDesc("账号黑名单存在");
                return result;
            }
            int insertCount = this.insertByEntitySelective(smsAccountBlacklist);
            result.setData(insertCount);
            //redis中添加accountBlacklist
            String key = String.format(JedisKey.SMS_BLACKLIST_ACCOUNT, smsAccountBlacklist.getAccount());
            JedisService.sadd(key, smsAccountBlacklist.getPhone());
            Map map = new HashMap();
            map.put("method", SubscribeEnum.ADDMOBILE.method);
            map.put("phone", smsAccountBlacklist.getPhone());
            map.put("account", smsAccountBlacklist.getAccount());
            JedisService.publish(JedisKey.SMS_SUBSCRIBE_API_ACTION, JSON.toJSONString(map));
            logger.info("addAccountBlacklist{}:...");
        } catch (Exception e) {
            logger.error("add account blacklist error....", e);
            result.setCode(BaseResultCode.SYSTEM_ERROR.getCode());
        }
        return result;
    }

    public boolean isExistAccountBlacklist(SmsAccountBlacklist smsAccountBlacklist) {
        int count = smsAccountBlacklistMapper.selectAccountBlacklist(smsAccountBlacklist);
        return count > 0 ? true : false;
    }


}
